#include <iostream>
#include <cstring>
#include <string>
#include <strings.h>
#include <sys/types.h>
#include <sys/socket.h>
#include <arpa/inet.h>
#include <netinet/in.h>

#include "log.hpp"

Log lg;
size_t size = 1024;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"<< std::endl;
}

int main(int argc ,char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        return 1;
    }

    std::string ip = argv[1];    
    std::uint16_t port = std::stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server,sizeof(server));
    server.sin_family = AF_INET;
    server.sin_port = htons(port);
    server.sin_addr.s_addr = inet_addr(ip.c_str());

 
    int sockfd = socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd < 0)
    {
        lg(fatal,"sock error: errno:%d,error:%s",errno,strerror(errno));
        return 1;
    }
    lg(info,"sock success");

    //bind
    socklen_t len = sizeof(server);

    // int n = bind(sockfd,(struct sockaddr*)&server,len);
    // if(n < 0)
    // {
    //     lg(fatal,"Bind error,errno: %d ,error: %s",errno,strerror(errno));
    //     return 2;
    // }

    std::string message;
    while(true)
    {
        message.clear();
        std::cout << "Please Enter@: ";
        getline(std::cin,message);

        struct sockaddr_in tmp;
        bzero(&tmp,sizeof(tmp));
        socklen_t tmplen = sizeof(tmp);
        sendto(sockfd,message.c_str(),size,0,(struct sockaddr*)&server,len);
        //接受消息
        char buffer[size];
        ssize_t s = recvfrom(sockfd,&buffer,sizeof(buffer)-1,0,(struct sockaddr*)&tmp,&tmplen);
        if(s > 0)
        {
            buffer[s] = '\0';
            std::cout << buffer << std::endl;
        }
    }
    
    close(sockfd);

    return 0;
}